<template>
  <view class="expert-add-page">
    <view class="form-container">
      <!-- 基本信息 -->
      <view class="form-section">
        <view class="section-title">基本信息</view>
        
        <!-- 导师姓名 -->
        <view class="form-item">
          <view class="form-label">导师姓名 <text class="required">*</text></view>
          <view class="form-input-wrapper">
            <input 
              class="form-input" 
              type="text" 
              placeholder="请输入导师姓名" 
              v-model="formData.name"
              maxlength="50"
            />
          </view>
        </view>

        <!-- 花名 -->
        <view class="form-item">
          <view class="form-label">花名 <text class="required">*</text></view>
          <view class="form-input-wrapper">
            <input 
              class="form-input" 
              type="text" 
              placeholder="请输入花名" 
              v-model="formData.englishName"
              maxlength="50"
            />
          </view>
        </view>

        <!-- 性别 -->
        <view class="form-item clickable" @click="openGenderPicker">
          <view class="form-label">性别 <text class="required">*</text></view>
          <view class="form-value-wrapper">
            <text class="form-value">{{ genderLabel }}</text>
            <text class="iconfont icon-ic_rightarrow arrow-icon"></text>
          </view>
        </view>

        <!-- 手机号码 -->
        <view class="form-item">
          <view class="form-label">手机号码 <text class="required">*</text></view>
          <view class="form-input-wrapper">
            <input 
              class="form-input" 
              type="number" 
              placeholder="请输入手机号码" 
              v-model="formData.phone"
              maxlength="11"
            />
          </view>
        </view>

        <!-- 微信号 -->
        <view class="form-item">
          <view class="form-label">微信号 <text class="required">*</text></view>
          <view class="form-input-wrapper">
            <input 
              class="form-input" 
              type="text" 
              placeholder="请输入微信号" 
              v-model="formData.wechat"
              maxlength="50"
            />
          </view>
        </view>

        <!-- 头像上传 -->
        <view class="form-item">
          <view class="form-label">头像 <text class="required">*</text></view>
          <view class="avatar-upload-wrapper">
            <view class="avatar-preview" v-if="formData.avatar" @click="uploadAvatar">
              <image :src="formData.avatar" mode="aspectFill" />
              <view class="avatar-mask">
                <text class="iconfont icon-ic_camera"></text>
              </view>
            </view>
            <view class="avatar-upload-placeholder" v-else @click="uploadAvatar">
              <text class="iconfont icon-ic_camera"></text>
              <text class="upload-text">上传头像</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 教育信息 -->
      <view class="form-section">
        <view class="section-title">教育信息</view>
        
        <!-- 最高学历 -->
        <view class="form-item clickable" @click="openEducationPicker">
          <view class="form-label">最高学历 <text class="required">*</text></view>
          <view class="form-value-wrapper">
            <text class="form-value">{{ educationLabel }}</text>
            <text class="iconfont icon-ic_rightarrow arrow-icon"></text>
          </view>
        </view>

        <!-- 学位 -->
        <view class="form-item">
          <view class="form-label">学位 <text class="required">*</text></view>
          <view class="form-input-wrapper">
            <input 
              class="form-input" 
              type="text" 
              placeholder="例如：博士、硕士" 
              v-model="formData.academicDegree"
              maxlength="50"
            />
          </view>
        </view>

        <!-- 毕业院校 -->
        <view class="form-item">
          <view class="form-label">毕业院校 <text class="required">*</text></view>
          <view class="form-input-wrapper">
            <input 
              class="form-input" 
              type="text" 
              placeholder="请输入毕业院校" 
              v-model="formData.graduationSchool"
              maxlength="100"
            />
          </view>
        </view>

        <!-- 专业 -->
        <view class="form-item">
          <view class="form-label">专业 <text class="required">*</text></view>
          <view class="form-input-wrapper">
            <input 
              class="form-input" 
              type="text" 
              placeholder="请输入专业" 
              v-model="formData.major"
              maxlength="100"
            />
          </view>
        </view>
      </view>

      <!-- 职业信息 -->
      <view class="form-section">
        <view class="section-title">职业信息</view>
        
        <!-- 学术职称 -->
        <view class="form-item">
          <view class="form-label">学术职称 <text class="required">*</text></view>
          <view class="form-input-wrapper">
            <input 
              class="form-input" 
              type="text" 
              placeholder="例如：教授、副教授" 
              v-model="formData.academicTitle"
              maxlength="50"
            />
          </view>
        </view>

        <!-- 行政职务 -->
        <view class="form-item">
          <view class="form-label">行政职务</view>
          <view class="form-input-wrapper">
            <input 
              class="form-input" 
              type="text" 
              placeholder="例如：系主任、院长" 
              v-model="formData.administrativeTitle"
              maxlength="50"
            />
          </view>
        </view>

        <!-- 所属院系 -->
        <view class="form-item">
          <view class="form-label">所属院系</view>
          <view class="form-input-wrapper">
            <input 
              class="form-input" 
              type="text" 
              placeholder="请输入所属院系" 
              v-model="formData.department"
              maxlength="100"
            />
          </view>
        </view>

        <!-- 工作单位 -->
        <view class="form-item">
          <view class="form-label">工作单位</view>
          <view class="form-input-wrapper">
            <input 
              class="form-input" 
              type="text" 
              placeholder="请输入工作单位" 
              v-model="formData.workUnit"
              maxlength="100"
            />
          </view>
        </view>
      </view>

      <!-- 研究方向 -->
      <view class="form-section">
        <view class="section-title">研究方向</view>
        
        <!-- 研究方向 -->
        <view class="form-item description-item">
          <view class="form-label">研究方向 <text class="required">*</text></view>
          <view class="textarea-wrapper">
            <textarea 
              class="form-textarea" 
              placeholder="请输入研究方向，多个用逗号分隔，例如：机器学习,数据挖掘,自然语言处理"
              v-model="formData.researchDirection"
              maxlength="500"
            />
          </view>
        </view>

        <!-- 擅长领域 -->
        <view class="form-item description-item">
          <view class="form-label">擅长领域</view>
          <view class="textarea-wrapper">
            <textarea 
              class="form-textarea" 
              placeholder="请输入擅长领域，多个用逗号分隔"
              v-model="expertiseFieldsText"
              maxlength="500"
            />
          </view>
          <view class="form-tip">多个领域用逗号分隔，将自动转换为JSON格式</view>
        </view>
      </view>

      <!-- 其他信息 -->
      <view class="form-section">
        <view class="section-title">其他信息</view>
        
        <!-- 个人简介 -->
        <view class="form-item description-item">
          <view class="form-label">个人简介</view>
          <view class="textarea-wrapper">
            <textarea 
              class="form-textarea" 
              placeholder="请输入个人简介"
              v-model="formData.personalProfile"
              maxlength="2000"
            />
          </view>
        </view>

        <!-- 邮箱地址 -->
        <view class="form-item">
          <view class="form-label">邮箱地址 <text class="required">*</text></view>
          <view class="form-input-wrapper">
            <input 
              class="form-input" 
              type="text" 
              placeholder="请输入邮箱地址" 
              v-model="formData.email"
              maxlength="100"
            />
          </view>
        </view>

        <!-- 指导费用标准 -->
        <view class="form-item">
          <view class="form-label">指导费用标准(元/小时)</view>
          <view class="form-input-wrapper">
            <input 
              class="form-input" 
              type="digit" 
              placeholder="请输入指导费用" 
              v-model="formData.hourlyRate"
            />
          </view>
        </view>
      </view>
    </view>

    <!-- 底部提交按钮 -->
    <view class="bottom-action-bar">
      <button class="submit-btn" @click="submitForm">提交申请</button>
    </view>

    <!-- 选择器 -->
    <u-picker
      :show="showGenderPicker"
      :columns="genderColumns"
      keyName="label"
      @confirm="confirmGender"
      @cancel="showGenderPicker = false"
    ></u-picker>

    <u-picker
      :show="showEducationPicker"
      :columns="educationColumns"
      keyName="label"
      @confirm="confirmEducation"
      @cancel="showEducationPicker = false"
    ></u-picker>
  </view>
</template>

<script>
import { saveThesisSupervisor } from '@/api/thesis.js';
import { HTTP_REQUEST_URL, TOKENNAME } from '@/config/app.js';
import store from '@/store';

export default {
  data() {
    return {
      formData: {
        name: '',
        englishName: '',
        gender: null,
        phone: '',
        wechat: '',
        avatar: '',
        education: null,
        academicDegree: '',
        graduationSchool: '',
        major: '',
        academicTitle: '',
        administrativeTitle: '',
        department: '',
        workUnit: '',
        researchDirection: '',
        expertiseFields: '',
        personalProfile: '',
        email: '',
        hourlyRate: ''
      },
      expertiseFieldsText: '',
      showGenderPicker: false,
      showEducationPicker: false,
      genderOptions: [
        { label: '未知', value: 0 },
        { label: '男', value: 1 },
        { label: '女', value: 2 }
      ],
      educationOptions: [
        { label: '学士', value: 1 },
        { label: '硕士', value: 2 },
        { label: '博士', value: 3 },
        { label: '博士后', value: 4 }
      ]
    }
  },
  computed: {
    genderColumns() {
      return [this.genderOptions];
    },
    genderLabel() {
      const current = this.genderOptions.find(item => item.value === this.formData.gender);
      return current ? current.label : '请选择';
    },
    educationColumns() {
      return [this.educationOptions];
    },
    educationLabel() {
      const current = this.educationOptions.find(item => item.value === this.formData.education);
      return current ? current.label : '请选择';
    }
  },
  methods: {
    // 打开性别选择器
    openGenderPicker() {
      this.showGenderPicker = true;
    },
    confirmGender(e) {
      const idx = (e.indexs && e.indexs[0]) || 0;
      const option = this.genderOptions[idx];
      if (option) {
        this.formData.gender = option.value;
      }
      this.showGenderPicker = false;
    },
    // 打开学历选择器
    openEducationPicker() {
      this.showEducationPicker = true;
    },
    confirmEducation(e) {
      const idx = (e.indexs && e.indexs[0]) || 0;
      const option = this.educationOptions[idx];
      if (option) {
        this.formData.education = option.value;
      }
      this.showEducationPicker = false;
    },
    // 上传头像
    uploadAvatar() {
      // this.$util.uploadImageOne('upload/image', function(res) {
      //   console.log(res);
      // });

      this.$util.uploadImageOne({
        url:'upload/image',
        name:'multipart',
        model: "maintain",
        pid:0,
        count:1
      },(res)=>{
        console.log("上传头像成功", res);
        this.formData.avatar = res;
      });

      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const filePath = res.tempFilePaths[0];
          if (!filePath) return;

          const uploadUrl = `${HTTP_REQUEST_URL}/api/front/upload/image`;
          uni.showLoading({ title: '上传中...' });

          uni.uploadFile({
            url: uploadUrl,
            filePath,
            name: 'file',
            header: {
              'Content-Type': 'multipart/form-data',
              [TOKENNAME]: store.state.app.token || ''
            },
            success: (response) => {
              uni.hideLoading();
              if (response.statusCode === 200) {
                let data = {};
                try {
                  data = response.data ? JSON.parse(response.data) : {};
                } catch (error) {
                  console.error('解析上传响应失败:', error);
                }
                if (data.code === 200 && data.data) {
                  this.formData.avatar = data.data.url || data.data.image || '';
                  uni.showToast({
                    title: '头像上传成功',
                    icon: 'success'
                  });
                } else {
                  uni.showToast({
                    title: data.message || '上传失败',
                    icon: 'none'
                  });
                }
              } else {
                uni.showToast({
                  title: '上传失败',
                  icon: 'none'
                });
              }
            },
            fail: (err) => {
              uni.hideLoading();
              console.error('上传头像失败:', err);
              uni.showToast({
                title: '上传失败',
                icon: 'none'
              });
            }
          });
        },
        fail: (err) => {
          console.error('选择图片失败:', err);
          uni.showToast({
            title: '选择图片失败',
            icon: 'none'
          });
        }
      });
    },
    // 验证表单
    validateForm() {
      if (!this.formData.name || !this.formData.name.trim()) {
        uni.showToast({ title: '请输入导师姓名', icon: 'none' });
        return false;
      }
      if (!this.formData.englishName || !this.formData.englishName.trim()) {
        uni.showToast({ title: '请输入花名', icon: 'none' });
        return false;
      }
      if (this.formData.gender === null || this.formData.gender === undefined) {
        uni.showToast({ title: '请选择性别', icon: 'none' });
        return false;
      }
      if (!this.formData.phone || !this.formData.phone.trim()) {
        uni.showToast({ title: '请输入手机号码', icon: 'none' });
        return false;
      }
      const phoneReg = /^1[3-9]\d{9}$/;
      if (!phoneReg.test(this.formData.phone)) {
        uni.showToast({ title: '请输入正确的手机号码', icon: 'none' });
        return false;
      }
      if (!this.formData.wechat || !this.formData.wechat.trim()) {
        uni.showToast({ title: '请输入微信号', icon: 'none' });
        return false;
      }
      if (!this.formData.avatar || !this.formData.avatar.trim()) {
        uni.showToast({ title: '请上传头像', icon: 'none' });
        return false;
      }
      if (this.formData.education === null || this.formData.education === undefined) {
        uni.showToast({ title: '请选择最高学历', icon: 'none' });
        return false;
      }
      if (!this.formData.academicDegree || !this.formData.academicDegree.trim()) {
        uni.showToast({ title: '请输入学位', icon: 'none' });
        return false;
      }
      if (!this.formData.graduationSchool || !this.formData.graduationSchool.trim()) {
        uni.showToast({ title: '请输入毕业院校', icon: 'none' });
        return false;
      }
      if (!this.formData.major || !this.formData.major.trim()) {
        uni.showToast({ title: '请输入专业', icon: 'none' });
        return false;
      }
      if (!this.formData.academicTitle || !this.formData.academicTitle.trim()) {
        uni.showToast({ title: '请输入学术职称', icon: 'none' });
        return false;
      }
      if (!this.formData.researchDirection || !this.formData.researchDirection.trim()) {
        uni.showToast({ title: '请输入研究方向', icon: 'none' });
        return false;
      }
      if (!this.formData.email || !this.formData.email.trim()) {
        uni.showToast({ title: '请输入邮箱地址', icon: 'none' });
        return false;
      }
      // 邮箱格式验证
      const emailReg = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
      if (!emailReg.test(this.formData.email.trim())) {
        uni.showToast({ title: '请输入正确的邮箱地址', icon: 'none' });
        return false;
      }
      return true;
    },
    // 构建提交数据
    buildSubmitData() {
      const data = { ...this.formData };
      
      // 处理擅长领域：将逗号分隔的文本转换为JSON格式
      if (this.expertiseFieldsText && this.expertiseFieldsText.trim()) {
        const fields = this.expertiseFieldsText.split(',').map(f => f.trim()).filter(f => f);
        data.expertiseFields = JSON.stringify(fields);
      }
      
      // 处理数字类型字段
      if (data.hourlyRate) {
        data.hourlyRate = Number(data.hourlyRate);
      }
      
      // 移除空字符串字段
      Object.keys(data).forEach(key => {
        if (data[key] === '' || data[key] === null || data[key] === undefined) {
          delete data[key];
        }
      });
      
      return data;
    },
    // 提交表单
    async submitForm() {
      if (!this.validateForm()) {
        return;
      }
      
      uni.showLoading({ title: '提交中...' });
      
      try {
        const submitData = this.buildSubmitData();
        const res = await saveThesisSupervisor(submitData);
        
        uni.hideLoading();
        
        if (res.code === 200) {
          uni.showToast({
            title: res.message || '提交成功',
            icon: 'success',
            duration: 2000
          });
          
          setTimeout(() => {
            uni.navigateBack();
          }, 2000);
        } else {
          uni.showToast({
            title: res.message || '提交失败',
            icon: 'none'
          });
        }
      } catch (error) {
        uni.hideLoading();
        console.error('提交失败:', error);
        uni.showToast({
          title: error.message || '提交失败，请重试',
          icon: 'none'
        });
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.expert-add-page {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 120rpx;
}

.form-container {
  padding: 20rpx;
}

.form-section {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  
  .section-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 30rpx;
    padding-bottom: 20rpx;
    border-bottom: 1rpx solid #f0f0f0;
  }
}

.form-item {
  margin-bottom: 30rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  &.clickable {
    cursor: pointer;
  }
  
  &.description-item {
    margin-bottom: 30rpx;
  }
  
  .form-label {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 16rpx;
    display: block;
    
    .required {
      color: #ED6567;
      margin-left: 4rpx;
    }
  }
  
  .form-input-wrapper {
    background: #f8f8f8;
    border-radius: 12rpx;
    padding: 0 24rpx;
    height: 88rpx;
    display: flex;
    align-items: center;
  }
  
  .form-input {
    flex: 1;
    font-size: 28rpx;
    color: #333;
    background: transparent;
    border: none;
    height: 100%;
  }
  
  .form-value-wrapper {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: #f8f8f8;
    border-radius: 12rpx;
    padding: 0 24rpx;
    height: 88rpx;
    
    .form-value {
      font-size: 28rpx;
      color: #333;
    }
    
    .arrow-icon {
      font-size: 24rpx;
      color: #999;
    }
  }
  
  .textarea-wrapper {
    background: #f8f8f8;
    border-radius: 12rpx;
    padding: 20rpx 24rpx;
    min-height: 200rpx;
  }
  
  .form-textarea {
    width: 100%;
    font-size: 28rpx;
    color: #333;
    background: transparent;
    border: none;
    min-height: 160rpx;
    line-height: 1.6;
  }
  
  .form-tip {
    font-size: 24rpx;
    color: #999;
    margin-top: 12rpx;
  }
}

.avatar-upload-wrapper {
  display: flex;
  align-items: center;
  
  .avatar-preview {
    width: 160rpx;
    height: 160rpx;
    border-radius: 16rpx;
    overflow: hidden;
    position: relative;
    
    image {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    
    .avatar-mask {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.3);
      display: flex;
      align-items: center;
      justify-content: center;
      opacity: 0;
      transition: opacity 0.3s;
      
      .iconfont {
        font-size: 48rpx;
        color: white;
      }
    }
    
    &:active .avatar-mask {
      opacity: 1;
    }
  }
  
  .avatar-upload-placeholder {
    width: 160rpx;
    height: 160rpx;
    border-radius: 16rpx;
    border: 2rpx dashed #ddd;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background: #f8f8f8;
    
    .iconfont {
      font-size: 48rpx;
      color: #999;
      margin-bottom: 8rpx;
    }
    
    .upload-text {
      font-size: 24rpx;
      color: #999;
    }
  }
}

.bottom-action-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 20rpx 30rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.08);
  z-index: 100;
}

.submit-btn {
  width: 100%;
  height: 88rpx;
  background: #ED6567;
  color: white;
  border: none;
  border-radius: 44rpx;
  font-size: 32rpx;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  
  &:active {
    background: #d55a54;
  }
}
</style>

